package com.ship.dispatch.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.common.core.base.Page;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.log.annotation.Log;
import com.ship.common.log.enums.BusinessType;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.SpDispatchSchemeExecute;
//import com.ship.dispatch.bean.sys.SysUser;
import com.ship.dispatch.bean.SpFobSublease;
import com.ship.dispatch.bean.boats.info.*;
import com.ship.dispatch.service.ExportService;
import com.ship.dispatch.service.SpDispatchSchemeExecuteService;
//import com.ship.dispatch.service.sys.SysUserService;
import com.ship.dispatch.service.SpFobSubleaseService;
import com.ship.dispatch.service.shipBusiness.SmShipReportService;
import com.ship.system.api.RemoteUserService;
import com.ship.system.api.domain.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

import static com.ship.dispatch.util.NumberFormatUtil.decimalFormat;

/**
 * @author yl
 * @title SpDispatchSchemeDetailController
 * @description 调度方案下发执行-船运执行
 * @create 2023/12/19 0019
 */
@RestController
@RequestMapping("/spDispatchSchemeExecute/")
@Api(value = "spDispatchSchemeDetail", tags = "船运执行")
public class SpDispatchSchemeExecuteController {

    @Autowired
    SpDispatchSchemeExecuteService spDispatchSchemeExecuteService;

    @Autowired
    private ExportService exportService;

    @Resource
    private RemoteUserService remoteUserService;

    @Autowired
    SpFobSubleaseService spFobSubleaseService;

    /**
     * 船运执行方案下发执行列表
     * @param pageDto
     * @return
     */
    @PostMapping("/page")
    public JsonResult<Page<SpDispatchSchemeExecute>> page(@RequestBody SpDispatchSchemeExecute pageDto){
        Page<SpDispatchSchemeExecute> resultPage = spDispatchSchemeExecuteService.page(pageDto);
        List<SpDispatchSchemeExecute> executes = resultPage.getList();
        if(executes.size()>0){
            executes.forEach(item->{
                if(item.getAssigeners()!=null && item.getAssigeners().length()>0){
                    String[] ids = item.getAssigeners().split(",");
                    //List<Long> userIds = Arrays.stream(ids).map(s->Long.parseLong(s)).collect(Collectors.toList());
                    List<SysUser> users = remoteUserService.listByIds(item.getAssigeners());
                    StringBuilder builder = new StringBuilder();
                    for(SysUser user:users){
                        builder.append(user.getUserName()).append(",");
                    }
                    String result = builder.toString();
                    if(result.endsWith(",")) {
                        result = result.substring(0, result.lastIndexOf(","));
                    }
                    item.setAssigeners(result);
                }
            });
        }
        resultPage.setList(executes);
        return JsonResult.success(resultPage);
    }

    /**
     * 船运执行方案下发执行列表
     * @param dto
     * @return
     */
    @PostMapping("/page/export")
    @Log(title = "导出船运执行方案下发执行列表",businessType = BusinessType.EXPORT)
    public JsonResult pageExport(@RequestBody SpDispatchSchemeExecute dto){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(dto.getIds() != null && dto.getIds().size() > 0){
            queryWrapper.in("id",dto.getIds());
        }
        List<SpDispatchSchemeExecute> exportList = spDispatchSchemeExecuteService.pageExportList(dto, queryWrapper, new LinkedList<>());
        for (SpDispatchSchemeExecute dispatchSchemeExecute : exportList) {
            if (dispatchSchemeExecute.getStorageCapacity()!=null){
                String result = null;
                result = decimalFormat.format(dispatchSchemeExecute.getStorageCapacity());
                result = result+" m³";
                dispatchSchemeExecute.setStorageCapacityString(result);
            }
            dispatchSchemeExecute.setTradeTypeStr(dispatchSchemeExecute.getTradeTypeStr());
            dispatchSchemeExecute.setTradeBodyStr(dispatchSchemeExecute.getTradeBodyStr());
            dispatchSchemeExecute.setSellerTradeTypeStr(dispatchSchemeExecute.getSellerTradeTypeStr());
            dispatchSchemeExecute.setSellerTradeBodyStr(dispatchSchemeExecute.getSellerTradeBodyStr());
            dispatchSchemeExecute.setShipContractTypeStr(dispatchSchemeExecute.getShipContractTypeStr());
            dispatchSchemeExecute.setShipTradeBodyStr(dispatchSchemeExecute.getShipTradeBodyStr());
            dispatchSchemeExecute.setStatusStr(dispatchSchemeExecute.getStatusStr());
            if(dispatchSchemeExecute.getAssigeners()!=null && dispatchSchemeExecute.getAssigeners().length()>0){
                String[] ids = dispatchSchemeExecute.getAssigeners().split(",");
                //List<Long> userIds = Arrays.stream(ids).map(s->Long.parseLong(s)).collect(Collectors.toList());
                List<SysUser> users = remoteUserService.listByIds(dispatchSchemeExecute.getAssigeners());
                StringBuilder builder = new StringBuilder();
                for(SysUser user:users){
                    builder.append(user.getUserName()).append(",");
                }
                String result = builder.toString();
                if(result.endsWith(",")) {
                    result = result.substring(0, result.lastIndexOf(","));
                }
                dispatchSchemeExecute.setAssigeners(result);
            }

        }
        Field[] fields = SpDispatchSchemeExecute.class.getDeclaredFields();
        String url = exportService.pageExport(exportList,fields,exportService.listStrByModuleAndUser
                ("sp_dispatch_scheme_execute", SecurityUtils.getUserId()), "船运执行货运详情信息");
        return JsonResult.success(url);
    }

    /**
     * 统计方案执行情况 shipContractType  1  长期船 2 短期船
     * @return  staus null 未开启，0 进行中 1 已完成 -1 中止
     */
    @GetMapping("/scheme/info")
    public JsonResult countSchemeInfo(@RequestParam(value = "planYear",required = false) String planYear){
        return spDispatchSchemeExecuteService.countSchemeInfo(planYear);
    }

    @ApiOperation("获取船运执行详情")
    @GetMapping("/get/{id}")
    public JsonResult getExecute(@PathVariable("id") Long id){
        SpDispatchSchemeExecute execute = spDispatchSchemeExecuteService.getById(id);
        if(execute==null){
            SpFobSublease spFobSublease = spFobSubleaseService.getById(id);
            return JsonResult.success(spFobSublease);
        }
        return JsonResult.success(execute);
    }


    /**
     * 删除执行记录ID
     * @param id
     * @return
     */
    @DeleteMapping("/remove/{id}")
    @Log(title = "删除执行记录ID",businessType = BusinessType.DELETE)
    public JsonResult deleteExecute(@PathVariable("id") Long id){
        return spDispatchSchemeExecuteService.deleteEexecute(id);
    }

    @ApiOperation("根据ID查询船运追踪-航速、吃水航向趋势图")
    @GetMapping("/query/ais/list")
    public JsonResult queryAisByShipName(@RequestParam Long id) throws ParseException {
        List<QueryAisInfo> aisList = spDispatchSchemeExecuteService.queryAisByShipName(id);
        return JsonResult.success(aisList);
    }

    @ApiOperation("根据ID查询船运追踪-油耗趋势图")
    @GetMapping("/query/fuelConsumptionTrend")
    public JsonResult queryFuelConsumptionTrend(@RequestParam Long id){
        List<QueryFuelConsumptionTrendInfo> reportList = spDispatchSchemeExecuteService.queryFuelConsumptionTrend(id);
        return JsonResult.success(reportList);
    }

    @ApiOperation("根据ID查询船运追踪-蒸发趋势图")
    @GetMapping("/query/evaporationConsumptionTrend")
    public JsonResult queryEvaporationConsumptionTrend(@RequestParam Long id){
        List<QueryEvaporationConsumptionTrendInfo> reportList = spDispatchSchemeExecuteService.queryEvaporationConsumptionTrend(id);
        return JsonResult.success(reportList);
    }

    @ApiOperation("船运追踪海图根据船舶名称获取mmsi")
    @GetMapping("/query/shipMmsiById")
    public JsonResult queryMmsiByShipName(@RequestParam Long id){
        QueryShipTraceInfo info = spDispatchSchemeExecuteService.queryMmsiByShipName(id);
        return JsonResult.success(info);
    }

    @ApiOperation("根据ID获取船舶事件信息")
    @GetMapping("/query/boatsEventMessage/byId")
    public JsonResult queryBoatsEventMessageById(@RequestParam Long id){
        List<BoatsEventMessageInfo> eventMessageList = spDispatchSchemeExecuteService.queryBoatsEventMessageById(id);
        return JsonResult.success(eventMessageList);
    }


}
